<style lang="less">
@import "../../../styles/tree-common.less";
@import "./departmentManage.less";
</style>
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <!-- <Button
          @click="add('up')"
          type="default"
          icon="md-add"
          v-show="showType === 'tree'"
          >在上方</Button
        >
        <Button
          @click="add('down')"
          type="default"
          icon="md-add"
          v-show="showType === 'tree'"
          >在下方</Button
        > -->
        <Button
          @click="add"
          type="primary"
          icon="md-add"
          v-show="showType === 'tree'"
          >添加子部门</Button
        >
        <Button @click="addRoot" icon="md-add">添加一级部门</Button>
        <Button @click="delAll" icon="md-trash">批量删除</Button>
        <Button @click="getParentList" icon="md-refresh">刷新</Button>
        <Button @click="editDeptName" type="primary" icon="ios-create-outline"
          >修改部门名称</Button
        >
        <Input
          v-model="searchKey"
          suffix="ios-search"
          @on-change="search"
          placeholder="输入部门名搜索"
          clearable
          style="width: 250px"
          v-show="showType === 'list'"
        />
        <i-switch
          v-model="strict"
          size="large"
          v-show="showType === 'tree'"
          style="margin-left: 5px"
        >
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch>
        <div style="float: right">
          <RadioGroup v-model="showType" type="button">
            <Radio title="树结构" label="tree">
              <Icon type="md-list"></Icon>
            </Radio>
            <Radio title="列表" label="list">
              <Icon type="ios-apps"></Icon>
            </Radio>
          </RadioGroup>
        </div>
      </Row>
      <Row type="flex" justify="start" v-show="showType === 'tree'">
        <Col span="8">
          <Alert show-icon>
            当前选择编辑：
            <span class="select-title">{{ editTitle }}</span>
            <a class="select-clear" v-if="form.id" @click="cancelEdit"
              >取消选择</a
            >
          </Alert>
          <Input
            v-model="searchKey"
            suffix="ios-search"
            @on-change="search"
            placeholder="输入部门名搜索"
            clearable
          />
          <div class="tree-bar" :style="{ maxHeight: maxHeight }">
            <Tree
              ref="tree"
              :data="data"
              :load-data="loadData"
              show-checkbox
              @on-check-change="changeSelect"
              @on-select-change="selectTree"
              :check-strictly="!strict"
            ></Tree>
            <Spin size="large" fix v-if="loading"></Spin>
          </div>
        </Col>
        <Col span="15" style="margin-left: 10px">
          <Row style="margin-bottom: 10px">
            <Button icon="md-add" type="primary" @click="addMember"
              >添加人员</Button
            >
          </Row>
          <Row>
            <Table
              :loading="loading"
              border
              :columns="userColumns"
              :data="users"
              ref="user"
              sortable="custom"
              @on-sort-change="changeSort"
              @on-selection-change="changeSelect"
            ></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page
              :current="searchForm.pageNumber" :total="total" simple
            ></Page>
          </Row>
        </Col>
      </Row>
      <Alert show-icon v-show="showType === 'list'">
        已选择
        <span class="select-count">{{ selectCount }}</span> 项
        <a class="select-clear" @click="clearSelectAll">清空</a>
      </Alert>
      <Table
        row-key="title"
        :load-data="loadData"
        :columns="columns"
        :data="data"
        :loading="loading"
        border
        ref="table"
        @on-selection-change="showSelect"
        v-if="showType === 'list'"
      ></Table>
    </Card>

    <Modal
      :title="modalTitle"
      v-model="modalVisible"
      :mask-closable="false"
      :width="500"
    >
      <Form
        ref="formAdd"
        :model="formAdd"
        :label-width="85"
        :rules="formValidate"
      >
        <div v-if="showParent">
          <FormItem label="上级部门：">{{ form.title }}</FormItem>
        </div>
        <!-- <FormItem label="部门位置" prop="position">
          <Select v-model="formAdd.position">
            <Option value="1">在选定部门上方添加部门</Option>
            <Option value="2">在选定部门下方添加部门</Option>
          </Select>
        </FormItem> -->
        <FormItem label="部门名称" prop="title">
          <label>
            <Input v-model="formAdd.title" />
          </label>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd"
          >提交</Button
        >
      </div>
    </Modal>

    <Modal
      title="修改部门名称"
      v-model="editVisible"
      :mask-closable="false"
      :width="500"
    >
      <Form ref="form" :model="form" :label-width="100" :rules="formValidate">
        <FormItem label="部门名称" prop="title">
          <Input v-model="form.title" />
        </FormItem>
        <Form-item class="br">
          <Button
            @click="submitEdit"
            :loading="submitLoading"
            type="primary"
            icon="ios-create-outline"
            >修改并保存</Button
          >
          <Button @click="handleReset">重置</Button>
        </Form-item>
      </Form>
    </Modal>

    <!-- 添加人员 -->
    <addEdit
      :data="form"
      :type="showUserType"
      v-model="showUser"
      @on-submit="getUserList"
    />
  </div>
</template>

<script>
import {
  initDepartment,
  loadDepartment,
  addDepartment,
  editDepartment,
  deleteDepartment,
  searchDepartment,
  getUserByDepartmentId,
  initDepartmentByLevel,
  getEnterpriseEmployeeList,
} from "@/api/index";
import addEdit from "./enterpriseEmployeeEdit.vue";
export default {
  name: "department-manage",
  components: {
    addEdit,
  },
  data() {
    return {
      showType: "tree",
      showUser: false,
      showUserType: 0,
      loading: true,
      maxHeight: "500px",
      strict: true,
      userLoading: false,
      loadingEdit: true,
      modalVisible: false,
      selectList: [],
      selectCount: 0,
      showParent: false,
      modalTitle: "",
      editTitle: "",
      searchKey: "",
      status: 0,
      form: {
        id: "",
        title: "",
        parentId: "",
        // parentTitle: "",
        // sortOrder: 0,
        // status: 0
      },
      formAdd: {},
      formValidate: {
        title: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      },
      submitLoading: false,
      data: [],
      dataEdit: [],
      users: [],
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          type: "index",
          width: 60,
          align: "center",
        },
        {
          title: "部门名称",
          key: "title",
          minWidth: 120,
          sortable: true,
          tree: true,
        },
        {
          title: "排序",
          key: "sortOrder",
          width: 150,
          sortable: true,
          align: "center",
          sortType: "asc",
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          width: 200,
        },
        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "md-add",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.tableAdd(params.row);
                    },
                  },
                },
                " 添加子部门"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      userColumns: [
        {
          title: '序号',
          key: "sort",
          width: 60,
          align: "center"
        },
        {
          title: "头像",
          key: "avatar",
          width: 150,
          align: "center",
          render: (h, params) => {
            return h("Avatar", {
              props: {
                src: params.row.avatar,
              },
            });
          },
        },
        {
          title: "用户名称",
          key: "nickname",
          minWidth: 120,
          align: "center"
        },
        {
          title: "岗位",
          key: "jobName",
          minWidth: 120,
          align: "center"
        },
        {
          title: "区域",
          key: "areaName",
          minWidth: 120,
          align: "center"
        },
        {
          title: "联系方式",
          key: "mobile",
          minWidth: 120,
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "md-up",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.upAdd(params.row);
                    },
                  },
                },
                "上方添加人员"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "default",
                    size: "small",
                    icon: "md-down",
                  },
                  on: {
                    click: () => {
                      this.downAdd(params.row);
                    },
                  },
                },
                "下方添加人员"
              ),
            ]);
          },
        },
      ],
      total: 0,
      searchForm: {
        departmentId: "",
        pageNumber: 1,
        pageSize: 10,
      },
      editVisible: false,
    };
  },
  methods: {
    init() {
      this.getParentList();
      this.getParentListEdit();
    },
    getParentList() {
      this.loading = true;
      initDepartmentByLevel().then((res) => {
        this.loading = false;
        if (res.success) {
          res.result.forEach(function (e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
              e._loading = false;
            }
          });
          this.data = res.result;
        }
      });
    },
    getParentListEdit() {
      this.loadingEdit = true;
      initDepartmentByLevel().then((res) => {
        this.loadingEdit = false;
        if (res.success) {
          res.result.forEach(function (e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          // 头部加入一级
          let first = {
            id: "0",
            title: "一级部门",
          };
          res.result.unshift(first);
          this.dataEdit = res.result;
        }
      });
    },
    loadData(item, callback) {
      loadDepartment(item.id).then((res) => {
        if (res.success) {
          res.result.forEach(function (e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
              e._loading = false;
            }
          });
          callback(res.result);
        }
      });
    },
    search() {
      if (this.searchKey) {
        this.loading = true;
        searchDepartment({ title: this.searchKey }).then((res) => {
          this.loading = false;
          if (res.success) {
            this.data = res.result;
          }
        });
      } else {
        this.getParentList();
      }
    },
    selectTree(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title;
        // 加载部门用户数据
        this.userLoading = true;
        this.searchForm.departmentId = data.id;
        this.form = data;
        getEnterpriseEmployeeList(this.searchForm).then((res) => {
          this.userLoading = false;
          console.log(res);
          if (res.code === 200) {
            this.total = res.result.size;
            this.users = res.result.content;
          } else {
            this.users = [];
            this.total = 0;
          }
        });
      } else {
        this.cancelEdit();
      }
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getUserList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getUserList();
    },
    getUserList() {
      getEnterpriseEmployeeList(this.searchForm).then((res) => {
        this.userLoading = false;
        console.log(res);
        if (res.success) {
          this.total = res.result.size;
          this.users = res.result.content;
        } else {
          this.users = [];
          this.total = 0;
        }
      });
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.id;
      this.editTitle = "";
    },
    selectTreeEdit(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.form.parentId = data.id;
        this.form.parentTitle = data.title;
      }
    },
    cancelAdd() {
      this.modalVisible = false;
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.form.status = 0;
    },
    showSelect(e) {
      this.selectList = e;
      this.selectCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    submitEdit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          editDepartment(this.form).then((res) => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("编辑成功");
              this.init();
              this.editVisible = false;
            }
          });
        }
      });
    },
    submitAdd() {
      this.$refs.formAdd.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          addDepartment(this.formAdd).then((res) => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("添加成功");
              this.init();
              this.modalVisible = false;
            }
          });
        }
      });
    },
    tableAdd(v) {
      this.form = v;
      this.add();
    },
    add() {
      if (this.form.id === "" || this.form.id == null) {
        this.$Message.warning("请先点击选择一个部门");
        return;
      }
      this.modalTitle = "添加子部门";
      this.showParent = true;
      this.formAdd = {
        parentId: this.form.id
      };
      this.modalVisible = true;
    },
    addRoot() {
      this.modalTitle = "添加一级部门";
      this.showParent = false;
      this.formAdd = {
        parentId: 0
      };
      this.modalVisible = true;
    },
    // 修改部门名称
    editDeptName() {
      if (this.form.id === "" || this.form.id == null) {
        this.$Message.warning("请先点击选择一个部门");
        return;
      }
      this.modalTitle = "修改部门名称";
      this.formAdd = {
        parentId: this.form.id,
      };
      this.editVisible = true;
    },
    changeSelect(v) {
      this.selectCount = v.length;
      this.selectList = v;
    },
    remove(v) {
      this.selectCount = 1;
      this.selectList.push(v);
      this.delAll();
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未勾选要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content:
          "您确认要删除所选的 " + this.selectCount + " 条数据及其下级所有数据?",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function (e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          deleteDepartment({ ids: ids }).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.selectList = [];
              this.selectCount = 0;
              this.cancelEdit();
              this.init();
            }
          });
        },
      });
    },
    addMember() {
      this.showUserType = "1";
      if (!this.form.id) {
        this.$Message.warning("请先点击要选择的部门");
        return;
      }
      this.showUser = true;
    },
    // 上方添加人员
    upAdd(row) {
      console.log(row);
      this.showUserType = "2";
      this.showUser = true;
    },
    // 下方添加人员
    downAdd(row) {
      console.log(row);
      this.showUserType = "3";
      this.showUser = true;
    },
  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  },
};
</script>
